package barinadroid.game;

import java.util.Random;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.entity.primitive.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;

public class MoveBackAndForthBehavior extends Behavior implements IUpdateHandler
{
	public static MoveBackAndForthBehavior getNewBehavior(GameEntity entity)
	{
		return new MoveBackAndForthBehavior(entity);
	}

	Vector2 pTo, pFrom;
	boolean flag;
	final float DURATION;
	float elapsed;

	private MoveBackAndForthBehavior(GameEntity entity)
	{
		super(entity);
		getEntity().getBody().setType(BodyType.DynamicBody);
		DURATION = .2f;
		Random d = new Random();
		Rectangle zone = GameScene.getSharedInstance().getSafeZone();
		pFrom = new Vector2(zone.getX() + zone.getWidth() * d.nextFloat(), zone.getY() + zone.getHeight() * d.nextFloat());
		pTo = new Vector2(zone.getX() + zone.getWidth() * d.nextFloat(), zone.getY() + zone.getHeight() * d.nextFloat());
		getEntity().getBody().setTransform(pFrom.x / 32, pFrom.y / 32, 0);
		setVelocity(this.flag=true);
		super.registerUpdateHandler(this);
	}

	@Override
	public void onUpdate(float pSecondsElapsed)
	{
		this.elapsed += pSecondsElapsed;
		if(elapsed > DURATION)
		{
			setVelocity(flag = !flag);
			float delta =elapsed - DURATION; 
			this.elapsed = 0;
			onUpdate(delta);
		}
		
		
//		this.elapsed += pSecondsElapsed;
//		Vector2 p = getEntity().getBody().getPosition();
//		float stepX = p.x * 32;
//		float stepY = p.y * 32;
//		if(flag)
//		{
//			stepX += (pFrom.x - pTo.x) / DURATION * pSecondsElapsed;
//			stepY += (pFrom.y - pTo.y) / DURATION * pSecondsElapsed;
//		}
//		else
//		{
//			stepX += (pTo.x - pFrom.x) / DURATION * pSecondsElapsed;
//			stepY += (pTo.y - pFrom.y) / DURATION * pSecondsElapsed;
//		}
//		getEntity().getBody().setTransform(stepX / 32, stepY / 32, 0);
//		if(elapsed > DURATION)
//		{
//			flag = !flag;
//			float delta = elapsed - DURATION;
//			elapsed = 0;
//			onUpdate(delta);
//		}
	}

	private void setVelocity(boolean flag)
	{
		Vector2 v = new Vector2();
		if(flag)
		{
			v.x = (pFrom.x - pTo.x) / (DURATION * 60);
			v.y = (pFrom.y - pTo.y) / (DURATION * 60);
		}
		else
		{
			v.x = (pTo.x - pFrom.x) / (DURATION * 60);
			v.y = (pTo.y - pFrom.y) / (DURATION * 60);
		}
		getEntity().getBody().setLinearVelocity(v);
	}

	@Override
	public void reset()
	{}
}